package com.edz;


import com.edawtech.module.BaseMsg;
import com.edawtech.module.LoginMsg;
import com.edawtech.module.MsgType;
import com.edawtech.module.PingMsg;
import com.edawtech.module.ReplyMsg;
import com.edawtech.module.ReplyServerBody;
import com.edz.message.deal.MessageCallable;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

/**
 * Created by yaozb on 15-4-11.
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<BaseMsg> {

    final int poolSize = 150;
    ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
    List<Future<String>> futures = new ArrayList<Future<String>>();  ///进行异步任务列表

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case WRITER_IDLE:
                    PingMsg pingMsg = new PingMsg();
                    ctx.writeAndFlush(pingMsg);
                    System.out.println("send ping to server----------");
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, BaseMsg baseMsg) throws Exception {
        MsgType msgType = baseMsg.getType();
        switch (msgType) {
            case LOGIN: {
                //向服务器发起登录
                LoginMsg loginMsg = new LoginMsg();
                loginMsg.setPassword("atom");
                loginMsg.setUserName("atom");
                channelHandlerContext.writeAndFlush(loginMsg);
            }
            break;
            case PING: {
                System.out.println("receive ping from server----------");
            }
            break;
//            case ASK:{
//                ReplyClientBody replyClientBody=new ReplyClientBody("client info **** !!!");
//                ReplyMsg replyMsg=new ReplyMsg();
//                replyMsg.setBody(replyClientBody);
//                channelHandlerContext.writeAndFlush(replyMsg);
//            }break;
            case REPLY: {
                ReplyMsg replyMsg = (ReplyMsg) baseMsg;
                ReplyServerBody replyServerBody = (ReplyServerBody) replyMsg.getBody();
                futures.add(threadPool.submit(new MessageCallable(channelHandlerContext, replyServerBody.getServerInfo())));
            }
            default:
                break;
        }
        ReferenceCountUtil.release(msgType);
    }
}
